<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactBatchAdd\Logic;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Plugin\ContactBatchAdd\Contract\ContactBatchAddAllotContract;
use MoChat\Plugin\ContactBatchAdd\Contract\ContactBatchAddImportContract;

/**
 * 导入客户-统计数据.
 *
 * Class Dashboard
 */
class DataStatisticLogic
{
    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var ContactBatchAddImportContract
     */
    protected $contactBatchAddImportService;

    /**
     * @Inject
     * @var ContactBatchAddAllotContract
     */
    protected $contactBatchAddAllotService;

    public function handle(array $params): array
    {
        $corpId = $params['corpId'];

        return [
            'employees' => $this->handleEmployees($params),
            'dataStatistic' => $this->getDataStatistic($corpId),
        ];
    }

    /**
     * @param int $params 企业ID
     * @return array 响应数组
     */
    private function handleEmployees(array $params): array
    {
        $where[] = [
            'corp_id', '=', $params['corpId'],
        ];

        if (! empty($params['employeeId'])) {
            $where[] = ['employee_id', 'in', $params['employeeId']];
        }

        if (! empty($params['startTime'])) {
            $where[] = ['created_at', '>=', $params['startTime'] . ' 00:00:00'];
            $where[] = ['created_at', '<=', $params['startTime'] . ' 23:59:59'];
        }
        $options = [
            'page' => $params['page'],
            'perPage' => $params['perPage'],
            'orderByRaw' => 'id desc',
        ];
        $statisticList = $this->contactBatchAddImportService->getContactBatchAddImportStatisticList($where, [Db::raw('employee_id, count(*) as allotNum, sum(if(status=0,1,0)) as recycleNum, sum(if(status=1,1,0)) as toAddNum, sum(if(status=2,1,0)) as pendingNum, sum(if(status=3,1,0)) as passedNum')], $options);
        if (empty($statisticList) || $statisticList['total'] == 0) {
            return [
                'page' => [
                    'perPage' => 20,
                    'total' => 0,
                    'totalPage' => 0,
                ],
                'list' => [],
            ];
        }

        $employeeIds = array_column($statisticList['data'], 'employeeId');
        $employees = $this->workEmployeeService->getWorkEmployeesById($employeeIds, ['id', 'name', 'avatar']);
        $employees = array_column($employees, null, 'id');

        $newStatistics = [];
        foreach ($statisticList['data'] as $key => &$item) {
            $newStatistics[$key] = $item;
            $item['name'] = isset($employees[$item['employeeId']]) ? $employees[$item['employeeId']]['name'] : '';
            // 待添加客户数
            $item['toAddNum'] = (int) $item['toAddNum'];
            // 待通过客户数
            $item['pendingNum'] = (int) $item['pendingNum'];
            // 已添加客户数
            $item['passedNum'] = (int) $item['passedNum'];
            // 回收客户数
            $item['recycleNum'] = (int) $item['recycleNum'];
            // 添加完成率
            $item['completion'] = intval($item['passedNum'] / ($item['allotNum'] ?: 1) * 10000) / 100;
        }

        $data = [
            'page' => [
                'perPage' => isset($statisticList['per_page']) ? $statisticList['per_page'] : 20,
                'total' => isset($statisticList['total']) ? $statisticList['total'] : 0,
                'totalPage' => isset($statisticList['last_page']) ? $statisticList['last_page'] : 0,
            ],
            'list' => empty($statisticList['data']) ? [] : $statisticList['data'],
        ];

        return $data;
    }

    private function getDataStatistic($corpId)
    {
        // 导入总客户数
        $result['contactNum'] = $this->contactBatchAddImportService->countContactBatchAddImportByStatus($corpId, 4);
        // 待分配客户数
        $result['pendingNum'] = $this->contactBatchAddImportService->countContactBatchAddImportByStatus($corpId, 0);
        // 待添加客户数
        $result['toAddNum'] = $this->contactBatchAddImportService->countContactBatchAddImportByStatus($corpId, 1);
        // 待通过客户数
        $result['toPendingNum'] = $this->contactBatchAddImportService->countContactBatchAddImportByStatus($corpId, 2);
        // 已添加客户数
        $result['passedNum'] = $this->contactBatchAddImportService->countContactBatchAddImportByStatus($corpId, 3);
        // 完成率
        $result['completion'] = intval($result['passedNum'] / ($result['contactNum'] ?: 1) * 10000) / 100;
        return $result;
    }
}
